package cn.com.dragonsoftbravo.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

public class ExcelUtil {

	private int totalRows = 0;

	private int totalCells = 0;

	private String errorInfo;

	public ExcelUtil() {

	}

	public int getTotalRows() {

		return totalRows;

	}

	public int getTotalCells() {

		return totalCells;

	}

	public String getErrorInfo() {

		return errorInfo;

	}

	public boolean validateExcel(String filePath) {

		if (filePath == null
				|| !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath) || WDWUtil.isCsv(filePath))) {

			errorInfo = "文件名不是excel格式";

			return false;

		}

		return true;

	}

	public List<List<String>> read(MultipartFile file) {

		List<List<String>> dataLst = new ArrayList<List<String>>();

		InputStream is = null;

		String filePath = file.getOriginalFilename();

		try {

			is = file.getInputStream();

			if (!validateExcel(filePath)) {

				System.out.println(errorInfo);

				return null;

			}

			int fileType = 0;

			if (WDWUtil.isExcel2007(filePath)) {
				fileType = 1;
			} else if (WDWUtil.isCsv(filePath)) {
				fileType = 2;
			}

			dataLst = read(is, fileType);

			is.close();

		} catch (Exception ex) {

			ex.printStackTrace();

		} finally {
			if (is != null) {

				try {

					is.close();

				} catch (IOException e) {

					is = null;

					e.printStackTrace();

				}

			}

		}

		return dataLst;
	}

	public List<List<String>> read(InputStream inputStream, int fileType) {

		List<List<String>> dataLst = null;

		try {

			Workbook wb = null;

			if (fileType == 0) {
				wb = new HSSFWorkbook(inputStream);
				dataLst = read(wb);
			} else if (fileType == 1) {
				wb = new XSSFWorkbook(inputStream);
				dataLst = read(wb);
			} else {
				dataLst = readCsv(new BufferedInputStream(inputStream));
			}

		} catch (IOException e) {

			e.printStackTrace();

		}

		return dataLst;

	}

	public static List<List<String>> readCsv(BufferedInputStream inputStream) {
		List<List<String>> dataList = new ArrayList<List<String>>();

		inputStream.mark(Integer.MAX_VALUE);
		
		BufferedReader br = null;
		InputStreamReader isr = null;

		try {
			isr = new InputStreamReader(inputStream, "GBK");
			br = new BufferedReader(isr);

			String line = "";
			List<String> rowList;

			int flag = 0;
			while ((line = br.readLine()) != null) {

				if (line.contains("[Content_Types]") && flag++ == 0) {
					inputStream.reset();
					
					Workbook wb = new XSSFWorkbook(inputStream);
					return new ExcelUtil().read(wb);
				}

				rowList = new ArrayList<String>();
				if (StringUtils.isNotBlank(line)) {
					String[] cells = line.split(",");
					for (String cell : cells) {
						rowList.add(cell.replace("\"", ""));
					}
				}
				dataList.add(rowList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
					br = null;
					isr.close();
					isr = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return dataList;
	}

	private List<List<String>> read(Workbook wb) {

		List<List<String>> dataLst = new ArrayList<List<String>>();

		Sheet sheet = wb.getSheetAt(0);

		this.totalRows = sheet.getPhysicalNumberOfRows();

		if (this.totalRows >= 1 && sheet.getRow(0) != null) {

			this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();

		}

		for (int r = 0; r < this.totalRows; r++) {

			Row row = sheet.getRow(r);

			if (row == null) {

				continue;

			}

			List<String> rowLst = new ArrayList<String>();

			for (int c = 0; c < this.getTotalCells(); c++) {

				Cell cell = row.getCell(c);

				String cellValue = "";

				if (null != cell) {
					// 以下是判断数据的类型
					switch (cell.getCellType()) {
					case HSSFCell.CELL_TYPE_NUMERIC: // 数字
						cellValue = cell.getNumericCellValue() + "";
						break;

					case HSSFCell.CELL_TYPE_STRING: // 字符串
						cellValue = cell.getStringCellValue();
						break;

					case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
						cellValue = cell.getBooleanCellValue() + "";
						break;

					case HSSFCell.CELL_TYPE_FORMULA: // 公式
						cellValue = cell.getCellFormula() + "";
						break;

					case HSSFCell.CELL_TYPE_BLANK: // 空值
						cellValue = "";
						break;

					case HSSFCell.CELL_TYPE_ERROR: // 故障
						cellValue = "非法字符";
						break;

					default:
						cellValue = "未知类型";
						break;
					}
				}

				rowLst.add(cellValue);

			}

			dataLst.add(rowLst);
		}
		return dataLst;
	}

	public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}

	public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
		List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
			public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
				return (o2.getValue()).compareTo(o1.getValue());
			}
		});

		Map<K, V> result = new LinkedHashMap<K, V>();
		for (Map.Entry<K, V> entry : list) {
			result.put(entry.getKey(), entry.getValue());
		}
		return result;
	}

}

class WDWUtil {

	public static boolean isExcel2003(String filePath) {

		return filePath.matches("^.+\\.(?i)(xls)$") || filePath.matches("^.+\\.(?i)(csv)$");

	}

	public static boolean isCsv(String filePath) {

		return filePath.matches("^.+\\.(?i)(csv)$");

	}

	public static boolean isExcel2007(String filePath) {

		return filePath.matches("^.+\\.(?i)(xlsx)$");

	}

}
